import React from 'react';
import { Box, Button, Paper } from '@mui/material';
import ContentCopyIcon from '@mui/icons-material/ContentCopy';

function MappingDisplay({ mappings, yInput }) {
  const generateMappingStructure = (ySchema, mappings) => {
    // 如果 yInput 不存在，返回空对象
    if (!ySchema) return {};

    const buildStructure = (obj, parentPath = '') => {
      if (Array.isArray(obj)) {
        return {
          toType: 'array',
          rules: buildStructure(obj[0], parentPath)?.rules || []
        };
      }

      if (typeof obj === 'object' && obj !== null) {
        const rules = [];
        
        Object.entries(obj).forEach(([key, value]) => {
          const currentPath = parentPath ? `${parentPath}.${key}` : key;
          
          if (typeof value === 'object' && value !== null) {
            if (Array.isArray(value)) {
              rules.push({
                to: key,
                toType: 'array',
                rules: buildStructure(value[0], currentPath)?.rules || []
              });
            } else {
              rules.push({
                to: key,
                toType: 'object',
                rules: buildStructure(value, currentPath)?.rules || []
              });
            }
          } else {
            // 查找该路径是否有映射关系
            const mapping = mappings.find(m => m.target === `result.${currentPath}`);
            rules.push({
              from: mapping ? mapping.source : '', // 如果没有映射，则为空字符串
              to: key,
              type: typeof value,
              ...(mapping?.formatter ? { formatter: mapping.formatter } : {}) // 只在有 formatter 时添加
            });
          }
        });

        return {
          toType: 'object',
          rules
        };
      }

      return null;
    };

    return buildStructure(ySchema);
  };

  const formatJson = (mappingStructure) => {
    return JSON.stringify(mappingStructure, null, 2);
  };

  const handleCopy = () => {
    if (yInput?.data) {
      const structure = generateMappingStructure(yInput.data, mappings);
      navigator.clipboard.writeText(formatJson(structure));
    }
  };

  return (
    <Paper 
      elevation={2} 
      sx={{ 
        height: '200px',
        display: 'flex',
        flexDirection: 'column',
        mb: 2,
        position: 'relative'
      }}
    >
      <Box sx={{ 
        p: 1, 
        borderBottom: '1px solid #e0e0e0',
        display: 'flex',
        justifyContent: 'space-between',
        alignItems: 'center',
        bgcolor: '#f5f5f5'
      }}>
        <span>映射关系</span>
        <Button
          size="small"
          variant="contained"
          startIcon={<ContentCopyIcon />}
          onClick={handleCopy}
          sx={{ minWidth: 'auto' }}
        >
          复制
        </Button>
      </Box>
      <Box 
        component="pre"
        sx={{
          flex: 1,
          overflow: 'auto',
          m: 0,
          p: 2,
          fontSize: '0.875rem',
          fontFamily: 'monospace',
          backgroundColor: '#fafafa',
          '&::-webkit-scrollbar': {
            width: '8px',
            height: '8px',
          },
          '&::-webkit-scrollbar-track': {
            backgroundColor: '#f1f1f1',
          },
          '&::-webkit-scrollbar-thumb': {
            backgroundColor: '#888',
            borderRadius: '4px',
            '&:hover': {
              backgroundColor: '#666',
            },
          },
        }}
      >
        {yInput?.data ? 
          formatJson(generateMappingStructure(yInput.data, mappings)) : 
          '等待Y输入数据...'}
      </Box>
    </Paper>
  );
}

export default MappingDisplay; 